var timer1, timer2, timer3;

var auth_uid = 0;  // 0:普通用户 id标识  1：管理员 id标识

var user_name;

var nick_name;

/***开发环境 测试环境  线上环境路径***/

/***cookie.min.js***/
(function(factory){if(typeof define==='function'&&define.amd){define(['jquery'],factory)}else if(typeof exports==='object'){factory(require('jquery'))}else{factory(jQuery)}}(function($){var pluses=/\+/g;function encode(s){return config.raw?s:encodeURIComponent(s)}function decode(s){return config.raw?s:decodeURIComponent(s)}function stringifyCookieValue(value){return encode(config.json?JSON.stringify(value):String(value))}function parseCookieValue(s){if(s.indexOf('"')===0){s=s.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,'\\')}try{s=decodeURIComponent(s.replace(pluses,' '));return config.json?JSON.parse(s):s}catch(e){}}function read(s,converter){var value=config.raw?s:parseCookieValue(s);return $.isFunction(converter)?converter(value):value}var config=$.cookie=function(key,value,options){if(value!==undefined&&!$.isFunction(value)){options=$.extend({},config.defaults,options);if(typeof options.expires==='number'){var days=options.expires,t=options.expires=new Date();t.setTime(+t+days*864e+5)}return(document.cookie=[encode(key),'=',stringifyCookieValue(value),options.expires?'; expires='+options.expires.toUTCString():'',options.path?'; path='+options.path:'',options.domain?'; domain='+options.domain:'',options.secure?'; secure':''].join(''))}var result=key?undefined:{};var cookies=document.cookie?document.cookie.split('; '):[];for(var i=0,l=cookies.length;i<l;i++){var parts=cookies[i].split('=');var name=decode(parts.shift());var cookie=parts.join('=');if(key&&key===name){result=read(cookie,value);break}if(!key&&(cookie=read(cookie))!==undefined){result[name]=cookie}}return result};config.defaults={};$.removeCookie=function(key,options){if($.cookie(key)===undefined){return false}$.cookie(key,'',$.extend({},options,{expires:-1}));return!$.cookie(key)}}));

$.extend({
    /*************加载...*************/
    windowMessage:function(){
        var $msg = '<div class="message"></div><div class="content-alert"></div><div class="loading"></div>';
        $('body').append($msg);
        window.onload = function (){
            $('.content-alert,.loading').hide();
        };
    },
    /**
     * 提取url中的参数
     * @param name string 参数名
     * @returns value|undefined
     */
    getQueryString:function(name){
        // var url = window.document.location.href.toString();
        var url =location.search
        var u = url.split("?");
        if(typeof(u[1]) == "string"){
            u = u[1].split("&");
            var get = {};
            for(var i in u){
                var j = u[i].split("=");
                get[j[0]] = j[1];
            }
            return get[name];
        } else {
            return undefined;
        }
    },
    /*************报错图补充*************/
    errorFigure:function(obj,img){
        obj.src = img;
    },
    /**
     * @param isAsync   默认异步
     * @param cache     默认不缓存
     * @param url       string 接口路径
     * @param params    Json   传输数据
     * @param callback  成功后的回调
     */
    apiGet:function(url,params,success,fail){
        $.ajax({
            url: url,
            type:'get',
            dataType : "json",
            data:params,
            xhrFields:{
                withCredentials:true
            },
            crossDomain:true,
            success: function(data) {
                if(success) success(data);
            },
            error: function (error) {
                if(fail) fail(error);
            }
        })
    },

    apiPost:function(url,params,success,fail){
        $.ajax({
            url: url,
            type:'post',
            dataType : "json",
            data:params,
            xhrFields:{
                withCredentials:true
            },
            crossDomain:true,
            success: function(data) {
                if(success) success(data);
            },
            error: function (error) {
                if(fail) fail(error);
            }
        });
    },
    /*************上传文件*************/
    apiUploadFiles:function(url,params,success,fail){
        $.ajax({
            url: url,
            data: params,
            type: "POST",
            dataType: "json",
            xhrFields:{
                withCredentials:true
            },
            crossDomain:true,
            cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
            contentType: false, //必须
            beforeSend:function(xhr){//请求之前
                var index = layer.load(1);
            },
            success: function (data) {
                if(success) success(data);
            },error:function(error){
                if(fail) fail(error);
            }
        });
    },
    /*************信息提示*************/
    messageShow:function(){
        var w = $('.message');
        w.addClass('messageShow');
    },
    messageHide:function(){
        var w = $('.message');
        w.css('display', 'none');
        w.removeClass('messageShow');
    },
    messageOut:function(){
        var w = $('.message');
        w.html('');
        w.removeClass('messageShow');
    },
    message:function(msg){
        var w = $('.message');
        clearTimeout(timer1);
        clearTimeout(timer2);
        clearTimeout(timer3);

        w.html(msg);
        w.css('display', 'block');

        timer1 = setTimeout("$.messageShow()", 80);
        timer2 = setTimeout("$.messageHide()", 2500);
        timer3 = setTimeout("$.messageOut()", 3000);
    },
    /**
     * 格式化时间
     *
     * @param time
     *            长整型时间
     * @param fmt
     *            时间格式，默认：yyyy-MM-dd
     * @returns
     */
    formatTime:function(time, fmt) {
        if (time == null) {
            return;
        }
        var fmt = fmt ? fmt : 'yyyy-MM-dd';
        var time = new Date(time);
        var z = {
            M: time.getMonth() + 1,
            d: time.getDate(),
            h: time.getHours(),
            m: time.getMinutes(),
            s: time.getSeconds()
        };
        fmt = fmt.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
            return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-2);
        });
        return fmt.replace(/(y+)/g, function(v) {
            return time.getFullYear().toString().slice(-v.length);
        });
    },
    getDifficultyHtml: function (level) {
        var strStyle = "";
        switch (level) {
            case 1:
                strStyle = '';
                break;
            case 2:
                strStyle = '';
                break;
            case 3:
                strStyle = '';
                break;
            case 4 :
                strStyle = '';
                break;
        }
        return strStyle;
    }
});
$.windowMessage();

/**普通用户TOP**/
var header_tml1 = '<div class="bannnerboxbg" onclick="show();">\n' +
    '            <div class="bannnerbox">\n' +
    '                <img src="../../static/images/index/logbg.png" href="" class="img01" width="1503" height="253">\n' +
    '              <img src="../../static/images/index/logo.png" href="" class="img02" width="600" height="600">\n' +
    '            \n' +
    '            </div>\n' +
    '        </div><div id="header_index" class="relative">\n' +
                '<div id="header-l">\n' +
    	            //'<img class="logo" src="../../static/images/index-logo.png" alt="">\n' +
    	            '<a href="../index/index.html" class="nav-a">首页</a>\n' +
    	            '<a href="../problem/problem.html" class="nav-a">问题</a>\n' +
    	            '<a href="../status/status.html" class="nav-a">状态</a>\n' +
    	            '<a href="../task/task.html" class="nav-a">作业</a>\n' +
    	            '<a href="../exam/exam.html" class="nav-a">考试</a>\n' +
    	            '<a href="../faq/faq.html" class="nav-a">FAQ</a>\n' +
                '</div>\n' +
            '<div id="header-r" class="absolute">\n' +
	            '<a href="javascript:;" class="c-fff float-left" id="userType"></a>\n' +
                '<a href="../user/seeBasicInfor.html#/seeInfo?index=0"><img id="avatar" class="float-left mt-15 ml-20 mr-10" src="../../static/images/user/avatar_default_01.png" alt="" ></a>\n' +
	            '<a href="../user/seeBasicInfor.html#/seeInfo?index=0" class="c-fff float-left mr-20" id="nickname"></a>\n' +
                '<a href="javascript:;" class="Logout" onclick="Logout()">Logout</a>\n' +
                '</div></div>';

var footer = 'Copyright © 2013-2019 ZJGSU ACM Club';

if($("#header").length>0){
    $("#header").html(header_tml1);
    getNickname();
    getUserType()
}
$("#footer").html(footer);

function getHref_path(){
    $(".menu .level2 a").removeClass("active");
    $(".menu .level1 i").removeClass("down");
    $(".menu .hurl").each(function(){
        var THIS_HREF = $(this);
        var href = THIS_HREF.attr("href");
        var a2 = location.href.substring(location.href.lastIndexOf("/")+1,location.href.length);
        var a1 = href.substring(href.lastIndexOf('/')+1,href.length);
        if(a1==a2) {
            THIS_HREF.addClass("active");
            THIS_HREF.closest(".level1").find("i").addClass("down");
        }
    });
}

/********管理员模块******/
var menu_html = '<ul class="menu"> '+
                    '<li class="level1"> '+
                        '<a href="javascript:;">新闻<i></i></a> '+
                        '<ul class="level2"> '+
                            '<li><a href="../admin/index.html#/newsList" class="hurl">新闻列表</a></li> '+
                            '<li><a href="../admin/index.html#/addnews" class="hurl">添加新闻</a></li>  '+
                        '</ul> '+
                    '</li> '+
                    '<li class="level1"> <a href="javascript:;">班级<i></i></a> '+
                        '<ul class="level2"> '+
                           ' <li><a href="../admin/index.html#/gradesList" class="hurl">班级列表</a></li> '+
                            '<li><a href="../admin/index.html#/addgradesList" class="hurl">添加班级</a></li>'+
                            '<li><a href="../admin/index.html#/addcoursesList" class="hurl">添加课程</a></li>'+
                        '</ul>'+ 
                    '</li> '+
                        '<li class="level1"> <a href="javascript:;">问题<i></i></a> '+
                            '<ul class="level2"> '+
                                '<li><a href="../admin/index.html#/problemList" class="hurl">问题列表</a></li> '+
                                '<li><a href="../admin/index.html#/addproblem" class="hurl">添加问题</a></li> '+
                            '</ul> '+
                        '</li> '+
                        '<li class="level1"> <a href="javascript:;">作业<i></i></a>'+ 
                            '<ul class="level2">'+ 
                                '<li><a href="../admin/index.html#/homeworkList" class="hurl">作业列表</a></li> '+
                                '<li><a href="../admin/index.html#/addhomeworkList" class="hurl">添加作业</a></li> '+
                            '</ul> '+
                        '</li> '+
                        '<li class="level1"> <a href="javascript:;">考试<i></i></a> '+
                            '<ul class="level2"> '+
                                '<li><a href="../admin/index.html#/examList" class="hurl">考试列表</a></li> '+
                                '<li><a href="../admin/index.html#/addexamList" class="hurl">添加考试</a></li> '+
                            '</ul>'+
                        '</li> '+
                        '<li class="level1"> <a href="javascript:;">用户<i></i></a> '+
                            '<ul class="level2"> '+
                                '<li><a href="../admin/index.html#/student" class="hurl">学生</a></li> '+
                                '<li><a href="../admin/index.html#/teacher" class="hurl">教师</a></li> '+
                                '<li><a href="../admin/index.html#/leader" class="hurl">课程负责人</a></li> '+
                                '<li><a href="../admin/index.html#/manager" class="hurl">管理员</a></li> '+
                            '</ul> '+
                        '</li> '+
                    '</ul>';

$(".treebox").html(menu_html);

$(function(){

    /****头部  及 个人中心侧边导航索引聚焦****/
    $("#header-l a.nav-a").each(function(){

        var THIS_HREF = $(this);
        var href = THIS_HREF.attr("href");
        var href1 = window.location.href ;
        var a1 = href.substring(href.lastIndexOf('/')+1,href.length);
        var a2 = href1.substring(href1.lastIndexOf("/")+1,href1.length);
        if(href1.length>href.length && a1==a2) {
            THIS_HREF.addClass("active");
            THIS_HREF.siblings("a.nav-a").removeClass("active");
        }
    });

    $(".treebox .level1>a").click(function(){
        var _this = $(this);

        if(_this.find('i').hasClass('down')){
            _this.find('i').removeClass('down'); 
            _this.closest("li.level1").find("ul").hide();
        }else{
            _this.find('i').addClass('down'); 
            _this.closest("li.level1").find("ul").show();
        }
        _this.closest("li.level1").siblings("li").find('a').find('i').removeClass('down');
        _this.closest("li.level1").siblings("li").find("ul").hide();        
         return false; 
    });
})

/**退出**/
function Logout() {
    $.ajax({
        url: logout_interface,
        type:'post',
        dataType:'json',
        xhrFields:{
            withCredentials:true
        },
        crossDomain:true,
        success: function(data) {
            if(data.code==200){
                setTimeout(function(){
                    location.href = '../user/login.html';
                },800);
            }else{
                $.message(data.msg);
            }
        },
        error: function () {
            $.message("链接超时，请刷新...");
        }
    });
}

function getNickname(){
    /**获取昵称**/
    $.ajax({
        url: get_nickname_interface,
        type:'post',
        dataType:'json',
        xhrFields:{
            withCredentials:true
        },
        crossDomain:true,
        success: function(data) {
            if(data.code==200){
                $("#nickname").html(data.data);
                nick_name=data.data;
            }else{
                $.message(data.msg);
            }
        },
        error: function () {
            $.message("链接超时，请刷新...");
        },
        async:false
    });
    return nick_name
}

function getUserName(){
    /**获取username(用户名)**/
    $.ajax({
        url: get_username_interface,
        type:'post',
        dataType:'json',
        xhrFields:{
            withCredentials:true
        },
        crossDomain:true,
        success: function(data) {
            if(data.code==200){
                user_name = data.data;
            }else{
                $.message(data.msg);
            }
        },
        error: function () {
            $.message("链接超时，请刷新...");
        },
        async:false
    });
    return user_name
}

function getUserType(){
    $.ajax({
        url: get_usertype_interface,
        type:'post',
        dataType:'json',
        xhrFields:{
            withCredentials:true
        },
        crossDomain:true,
        success: function(data) {
            if(data.code==200){
                auth_uid = data.data.user_type;
                if(auth_uid==4){
                    $("#userType").html('[admin]')
                    $("#userType").attr('href','../admin/index.html#/admin')
                }else if(auth_uid==3){
                    $("#userType").html('[head teacher]')
                }else if(auth_uid==2){
                    $("#userType").html('[teacher]')
                }else{
                    $("#userType").html('[student]')
                }
            }else{
                $.message(data.msg);
            }
        },
        error: function () {
            $.message("链接超时，请刷新...");
        },
        async:false
    });
    return auth_uid
}


function getrequest(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}

function fileinput(obj) {
    filedir=$(obj).val();
    filenames=filedir.split(/[/\\]/)
    filename=filenames[filenames.length-1]
    $(obj).closest("div.thefile").find(".filename").val(filename)
}